<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简易聊天框</title>
    <style type="text/css">
    </style>
</head>
<body>
<div style="flex-direction: column">
    <div>
        <label>
            <textarea rows="3" id="chatMsg" style="height: 500px;width: 500px;resize: none;"></textarea>
        </label>
    </div>
    <div>
        <label>
            <input type="text" style="width: 400px" name="inputMsg" id="inputMsg" onkeyup="inputChange(this.value)">
            <button type="button" onclick="sendMsg()">发送</button>
        </label>
    </div>
</div>
</body>
<script type="application/javascript">
    /**
     * 一般情况下，只需要改动self,other,websocket服务器地址即可使用
     */
    const self = "user_two";
    const other = "user_one";

    const message = {attr: ""};
    const input = document.getElementById("inputMsg");
    const chatMsg = document.getElementById("chatMsg");

    let websocket = {
        send: function (str) {
        }
    };
    window.onload = function () {
        if (!'WebSocket' in window) return;
        webSocketInit();
    };
    //初始化websocket
    function webSocketInit() {
        websocket = new WebSocket("ws://127.0.0.1:7777/person/" + self);
        //成功建立连接
        websocket.onopen = function () {
            linkSuccess(self, self, "链接成功");
        };
        //接收到消息
        websocket.onmessage = function (event) {
            const data = JSON.parse(event.data);
            chatMsg.value = chatMsg.value + data.from + " >>> " + data.message + "\n";
        };
        //连接发生错误
        websocket.onerror = function () {
            alert("WebSocket连接发生错误");
        };
        //连接关闭
        websocket.onclose = function () {
            alert("WebSocket连接关闭");
        };
        //监听窗口关闭事件，当窗口关闭时，主动关闭websocket连接
        window.onbeforeunload = function () {
            websocket.close()
        };
    }

    //对message.attr进行绑定
    Object.defineProperty(message, "attr", {
        configurable: true,
        enumerable: true,
        set: function (newValue) {
            attr = newValue;
            input.value = newValue
        },
        get: function () {
            return attr;
        },
    });
    function inputChange(newValue) {
        message.attr = newValue
        if (event.keyCode === 13 &&
            message.attr !== undefined && message.attr !== null && message.attr.length > 0) {
            sendMsg();
        }
    }

    //发送消息
    function sendMsg() {
        if (message.attr.length <= 0) {
            return
        }
        const msg = {
            from: self,
            to: other,
            createTime: new Date(),
            message: message.attr
        };
        chatMsg.value = chatMsg.value + msg.from + " >>> " + msg.message + "\n";
        websocket.send(JSON.stringify(msg))
        message.attr = ""
    }

    //链接成功
    function linkSuccess(from, to, msg) {
        const successMsg = {
            from: from,
            to: to,
            createTime: new Date(),
            message: msg
        };
        websocket.send(JSON.stringify(successMsg))
    }
</script>
</html>